//
//  M4ThirdInfoViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/12.
//

import UIKit
import AVFoundation
import Photos

class M4ThirdInfoViewController: M4BaseViewController {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.delegate = self
        scroll.backgroundColor = .white
        scroll.contentSize.width = M4ScreenWidth
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.addObserver(self, forKeyPath: "scrollViewWillBeginDragging", context: nil)
        return scroll
    }()
    
    lazy var tipImageView: M4InfosTopKycTipImageView = {
        
        let view = UINib(nibName: "M4InfosTopKycTipImageView", bundle: nil).instantiate(withOwner: self).last as! M4InfosTopKycTipImageView
        view.M4TipimageView.image = UIImage(named: "img_schedule3")
        
        view.setStyledCreditText(amountText: "$ 24,000",typestr: 3)
        
        return view
    }()
    
    lazy var bottomView: M4InfosBottomView = {
        let view = M4InfosBottomView()
        view.m4View.c = self
        view.m4BottomButtonBlock = { button in
            self.view.endEditing(true)
//            //提交信息
//            let vc = M4ThirdInfoViewController()
//            self.navigationController?.pushViewController(vc, animated: true)
            self.M4SubmitVerfication()
        }
        return view
    }()
    
    lazy var firstView: M4ThirdInfoFirstView = {
        let view = UINib(nibName: "M4ThirdInfoFirstView", bundle: nil).instantiate(withOwner: self).last as! M4ThirdInfoFirstView
        view.M4DescriptionView.c = self
        view.M4ShowTakePhotoBlock = {
            self.m4showUploadWay()
        }
        return view
    }()
    
    lazy var secondView: M4ThirdInfoSecondView = {
        let view = UINib(nibName: "M4ThirdInfoSecondView", bundle: nil).instantiate(withOwner: self).last as! M4ThirdInfoSecondView
        view.M4ImageButton.addTarget(self, action: #selector(m4showUploadWay), for: .touchUpInside)
        return view
    }()
    
    private var titles = ["Nombre", "Apellido paterno", "Apellido materno", "CURP"]
    
    private var m4inputTFViews: [M4InfosPublicView] = []
    
    private var m4frontImageUrl: String = ""
    
    private var m4enterTime: Int = 0
    
    deinit {
        scrollView.removeObserver(self, forKeyPath: "scrollViewWillBeginDragging")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Datos de la tarjeta de identidad", M4NavTitleColor: COLOR_333333)
        m4updateUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = .white
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        M4InfosPageBack()
        sender.M4EventUnavailable = false
        hgjyj1 = Int(Date().timeIntervalSince1970 * 1000)
        self.uploadData1()
    }
    
    private func m4updateUI() {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        scrollView.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
        scrollView.addSubview(firstView)
        firstView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(tipImageView.snp.bottom).offset(15)
            make.width.equalTo(M4ScreenWidth)
        }
    }
    
    private func m4changeUI() {
        if m4inputTFViews.count != 0 { return }
        m4inputTFViews.removeAll()
        firstView.isHidden = true
        scrollView.addSubview(secondView)
        secondView.snp.makeConstraints { make in
            make.top.equalTo(tipImageView.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
        for i in 0..<titles.count {
            let infoView = UINib(nibName: "M4InfosPublicView", bundle: nil).instantiate(withOwner: self).last as! M4InfosPublicView
            infoView.m4InfoPublicTitle.text = titles[i]
            infoView.m4InfoPublicDownIcon.isHidden = true
            infoView.m4InfoPublicDownRight.constant = 0
            infoView.m4InfoPublicDownWidth.constant = 0
            infoView.m4InfoPublicTF.delegate = self
            infoView.m4InfoPublicTF.tag = i
            m4inputTFViews.append(infoView)
            scrollView.addSubview(infoView)
            infoView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                if i == 0 {
                    make.top.equalTo(secondView.snp.bottom)
                }
                else {
                    make.top.equalTo(m4inputTFViews[i-1].snp.bottom)
                }
                
                make.width.equalTo(M4ScreenWidth)
                if i == titles.count - 1 {
                    scrollView.addSubview(bottomView)
                    bottomView.snp.makeConstraints { make in
                        make.top.equalTo(infoView.snp.bottom).offset(20)
                        make.left.right.equalToSuperview()
                        make.bottom.equalToSuperview().offset(-20)
                        make.width.equalTo(M4ScreenWidth)
                    }
                }
            }
        }
    }

    var asqwr = 0
    var hgjyj1 = 0
    func uploadData1() {
        let params: [[String:Any]] = [
            [
                "adga" : 6001,
                "sdqw" : inTime,
                "hgjyj" : sdqw,
                "asqwr" : 1,
            ],
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .IDCard, paramsKey: "sqwerqw", params: params, complete: nil)
    }
    
    
    var sdqw = 0
    var hgjyj = 0
    var fqwrf = 0
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 6002,
                "sdqw" : sdqw,
                "hgjyj" : hgjyj,
                "fqwrf" : fqwrf,
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .IDCard, paramsKey: "sqwerqw", params: params, complete: nil)
    }
}

extension M4ThirdInfoViewController {
    
    @objc private func m4showUploadWay() {
        let alert = UINib(nibName: "M4TakePhotoAlertView", bundle: nil).instantiate(withOwner: self).last as! M4TakePhotoAlertView
        alert.M4TakePhotoCamareBlock = {
            self.M4ShowCameraPage()
        }
        alert.M4TakePhotoAlbumBlock = {
            self.M4ShowSystemAlbum()
        }
        alert.M4PopViewShow(subview: alert.M4TakePhotoBGView)
        firstView.M4ShowTakePhotoButton.M4EventUnavailable = false
        secondView.M4ImageButton.M4EventUnavailable = false
    }
    
    private func M4ShowCameraPage() {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted {
                DispatchQueue.main.async {
                    let camareVC = M4ThirdCameraViewController()
                    camareVC.M4ThirdCameraImageBlock = { m4image in
                        guard let imgData = M4Image.M4ImageCompress(image: m4image, maxSize: 10*1024*1024) else {return}
                        let dataStr: String = imgData.base64EncodedString(options: [])
                        self.M4UploadAndOcrNet(imgStr: dataStr)
                        self.secondView.M4ShowIDImageView.image = m4image
                    }
                    self.navigationController?.pushViewController(camareVC, animated: true)
                }
            }else{
                DispatchQueue.main.async {
                    let alert = UINib(nibName: "M4LimitAlertView", bundle: nil).instantiate(withOwner: self).last as! M4LimitAlertView
                    alert.M4LimitAlertViewUpdate(nameArray: [["img": "icon_limit_camera", "name": "Cámara"]])
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    private func M4ShowSystemAlbum() {
        PHPhotoLibrary.requestAuthorization { [self] status in
            if (status == .authorized) {
                DispatchQueue.main.async {
                    let albumVC = UIImagePickerController()
                    albumVC.view.backgroundColor = .white
                    albumVC.delegate = self
                    albumVC.allowsEditing = true
                    albumVC.sourceType = .photoLibrary
                    albumVC.modalPresentationStyle = .fullScreen
                    self.present(albumVC, animated: true, completion: nil)
                }
            }else{
                DispatchQueue.main.async {
                    let alert = UINib(nibName: "M4LimitAlertView", bundle: nil).instantiate(withOwner: self).last as! M4LimitAlertView
                    alert.M4LimitAlertViewUpdate(nameArray: [["img": "icon_limit_album", "name": "Álbum"]])
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    private func M4ShowFailAlert() {
        let alert = UINib(nibName: "M4TakeFailTipsView", bundle: nil).instantiate(withOwner: self).last as! M4TakeFailTipsView
        alert.M4TakeFailResetBlock = {
            self.m4showUploadWay()
        }
        alert.M4AlertViewShow()
    }
    
}

extension M4ThirdInfoViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
        picker.dismiss(animated: true, completion: nil)
        let img = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        guard let imgData = M4Image.M4ImageCompress(image: img, maxSize: 10*1024*1024) else {return}
        let dataStr: String = imgData.base64EncodedString(options: [])
        self.M4UploadAndOcrNet(imgStr: dataStr)
        self.secondView.M4ShowIDImageView.image = img
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
        picker.dismiss(animated: true, completion: nil)
    }
}

extension M4ThirdInfoViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let index = textField.tag
        m4inputTFViews[index].m4InfoPublicError.text = ""
        guard let textString = textField.text else {return true}
        let length = textString.count + string.count - range.length
        if textField != m4inputTFViews[3].m4InfoPublicTF {
            if (range.location == 0 && string == " ") || length > 30 {
                return false
            }
        }
        else {
            if length > 18 || string == " " {
                return false
            }
            //判断输入的是否是数字和字母
            let allowedCharacters = CharacterSet.decimalDigits.union(.letters)
            let characterSet = CharacterSet(charactersIn: string)
            return allowedCharacters.isSuperset(of: characterSet)
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField != m4inputTFViews[3].m4InfoPublicTF {
            textField.text = textField.text?.trimmingCharacters(in: .whitespaces)
        }
        else {
            textField.text = textField.text?.uppercased()
        }
    }
    
}

extension M4ThirdInfoViewController {
    
    private func M4UploadAndOcrNet(imgStr: String) {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        M4PublicNetwork.M4UploadFielNet(imgBase64Str: imgStr) { success, urlstring in
            if success {
                self.M4OcrNet(fielString: urlstring, loading: loading)
            }
            else {
                loading.M4AlertViewHidden()
                self.M4ShowFailAlert()
            }
        }
    }
    
    private func M4OcrNet(fielString: String, loading: M4LoadingAlertView) {
        let param: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 7, "FGVoB": fielString]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param), false) { model in
            loading.M4AlertViewHidden()
            if model.code == 1 {
                self.sdqw = Int(Date().timeIntervalSince1970 * 1000)
                self.m4changeUI()
                self.m4frontImageUrl = fielString
                let data = model.data as? [String : Any]
                self.m4inputTFViews[0].m4InfoPublicTF.text = data?["Vor"] as? String
                self.m4inputTFViews[1].m4InfoPublicTF.text = data?["KpEmQtaED"] as? String
                self.m4inputTFViews[2].m4InfoPublicTF.text = data?["MWMNZW"] as? String
                self.m4inputTFViews[3].m4InfoPublicTF.text = data?["CLif"] as? String
            }
            else {
                self.M4ShowFailAlert()
            }
        }
    }
    
    private func M4SubmitVerfication() {
        if m4frontImageUrl == "" {
            self.view.makeToast("Por favor, cargue una foto del frente de su cédula de identidad", position: .center)
            self.bottomView.m4submitButton.M4EventUnavailable = false
            return
        }
        for j in 0..<m4inputTFViews.count {
            if m4inputTFViews[j].m4InfoPublicTF.text?.count == 0 {
                let msg = j == m4inputTFViews.count - 1 ? "Ingrese el CURP en el formato correcto" : "Ingrese el nombre en el formato correcto"
                m4inputTFViews[j].m4InfoPublicError.text = msg
//                self.view.makeToast(msg, position: .center)
                self.bottomView.m4submitButton.M4EventUnavailable = false
                return
            }
        }
        let alert = UINib(nibName: "M4IDCardInfoConfrimView", bundle: nil).instantiate(withOwner: self).last as! M4IDCardInfoConfrimView
        alert.M4IDCardUpdateUI(name: m4inputTFViews[0].m4InfoPublicTF.text ?? "", faname: m4inputTFViews[1].m4InfoPublicTF.text ?? "", maname: m4inputTFViews[2].m4InfoPublicTF.text ?? "", idnumber: m4inputTFViews[3].m4InfoPublicTF.text ?? "")
        alert.M4ConfirmBlock = {
            self.M4SubmitThirdInfoNet()
        }
        
        
        self.view.addSubview(alert)
        alert.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
            alert.alpha = 1
            alert.transform = CGAffineTransform.identity
        }
        alert.M4DecirptionView.c = self
//        alert.M4AlertViewShow()
        self.bottomView.m4submitButton.M4EventUnavailable = false
    }
    
    private func M4SubmitThirdInfoNet() {
        asqwr = 1
        fqwrf = Int(Date().timeIntervalSince1970  * 1000)
        let m4endTime = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        let param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 4, "RYO": m4endTime, "FGVoB": m4frontImageUrl, "DOfZiJ": m4inputTFViews[0].m4InfoPublicTF.text ?? "", "HmqBG": m4inputTFViews[1].m4InfoPublicTF.text ?? "", "KkojQeW": m4inputTFViews[2].m4InfoPublicTF.text ?? "", "GAhd": m4inputTFViews[3].m4InfoPublicTF.text ?? ""]
        
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.bottomView.m4submitButton.M4EventUnavailable = false
            if model.code == 1 {
                let vc = M4FourInfoViewController()
                self.navigationController?.pushViewController(vc, animated: true)
                self.hgjyj = Int(Date().timeIntervalSince1970  * 1000)
                self.uploadData()
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
}
